//
//  HHNavBarIndicatorView.m
//  HHChatKit
//
//  Created by Henry on 2021/8/11.
//

#import "HHNavBarIndicatorView.h"

#define NavBar_Height       (50)
#define IOS8_10 ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0 && [[UIDevice currentDevice].systemVersion doubleValue] < 10.0)

@implementation HHNavBarIndicatorView

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self setupViews];
    }
    return self;
}

- (void)setupViews {
    _indicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
    _indicator.center = CGPointMake(0, NavBar_Height * 0.5);
    _indicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhite;
    [self addSubview:_indicator];

    _label = [[UILabel alloc] init];
    _label.backgroundColor = [UIColor clearColor];
    _label.font = [UIFont boldSystemFontOfSize:17];
    _label.textColor = [UIColor blackColor];
    [self addSubview:_label];
}

- (void)setTitle:(NSString *)title {
    _label.text = title;
    [self updateLayout];
}

- (void)updateLayout {
    CGSize labelSize = [_label sizeThatFits:CGSizeMake([UIScreen mainScreen].bounds.size.width, NavBar_Height)];
    CGFloat labelY = 0;
    CGFloat labelX = _indicator.hidden ? 0 : (_indicator.frame.origin.x + _indicator.frame.size.width + 5);
    _label.frame = CGRectMake(labelX, labelY, labelSize.width, NavBar_Height);
    CGFloat width = labelX + labelSize.width + 5;
    CGFloat xx = ([UIScreen mainScreen].bounds.size.width - width)/2;
    if (IOS8_10) {
        self.frame = CGRectMake(xx, 0, width, NavBar_Height);
    } else {
        self.frame = CGRectMake(0, 0, width, NavBar_Height);
    }
}

- (CGSize)intrinsicContentSize {
    return UILayoutFittingExpandedSize;
}

- (void)startAnimating {
    [_indicator startAnimating];
}

- (void)stopAnimating {
    [_indicator stopAnimating];
}

@end
